<?php
/**
 * 支付回调
 *
 *
 *
 *
 * @copyright  Copyright (c) 2007-2013 BesonIT Inc. (http://www.besonit.com)
 * @license    http://www.besonit.com
 * @link       http://www.besonit.com
 * @since      File available since Release v1.1
 */


defined('BYshopJL') or exit('Access Invalid!');

class paymentControl extends wxHomeControl
{

    private $payment_code;

    public function __construct()
    {
        parent::__construct();

        $this->payment_code = $_GET['payment_code'];
    }

    /**
     * 支付回调
     */
    public function returnOp()
    {
        unset($_GET['act']);
        unset($_GET['op']);
        unset($_GET['payment_code']);

        $payment_api = $this->_get_payment_api();

        $payment_config = $this->_get_payment_config();

        $callback_info = $payment_api->getReturnInfo($payment_config);

        if ($callback_info) {
            //验证成功
            $result = $this->_update_order($callback_info['out_trade_no'], $callback_info['trade_no']);
            if ($result['state']) {
                Tpl::output('result', 'success');
                Tpl::output('message', '支付成功');
            } else {
                Tpl::output('result', 'fail');
                Tpl::output('message', '支付失败');
            }
        } else {
            //验证失败
            Tpl::output('result', 'fail');
            Tpl::output('message', '支付失败');
        }

        Tpl::showpage('payment_message');
    }

    /**
     * 支付提醒
     */
    public function notifyOp()
    {


        // 恢复框架编码的post值
        $_POST['notify_data'] = html_entity_decode($_POST['notify_data']);

        $payment_api = $this->_get_payment_api();

        $payment_config = $this->_get_payment_config();

        $callback_info = $payment_api->getNotifyInfo($payment_config);

        if ($callback_info) {
            //验证成功
            $result = $this->_update_order($callback_info['out_trade_no'], $callback_info['trade_no']);
            if ($result['state']) {
                echo 'success';
                die;
            }
        }

        //验证失败
        echo "fail";
        die;
    }

    public function wxnotifyOp()
    {
        include_once(API_PATH . "/payment/wxpay/WxPayPubHelper/WxPayPubHelper.php");
        $Notify = new Notify_pub();

        //接收微信推送过来的数据 xml
        $xml = '';
        $Notify->saveData($GLOBALS['HTTP_RAW_POST_DATA']);

        //file_put_contents('Notify.txt',var_export($Notify,true));

        //验证sign
        if ($Notify->checkSign() && $Notify->data['return_code'] && $Notify->data['result_code']) {

            $order_pay_info = Model('wx_order')->getOrderPayInfo(array('pay_sn' => $Notify->data['out_trade_no']));
            //file_put_contents('order_pay_info.txt',var_export($order_pay_info,true));
            if ($order_pay_info['api_pay_state'] != 1) {
                $result = $this->_update_order($Notify->data['out_trade_no'], $Notify->data['transaction_id']);

                //file_put_contents('result.txt',var_export($result,true));
                if ($result['state']) {
                    $Notify->setReturnParameter('return_code', 'SUCCESS');//处理成功
                } else {
                    $Notify->setReturnParameter('return_code', 'FAIL');
                }
            } else {
                $Notify->setReturnParameter('return_code', 'SUCCESS');//已经处理过
            }

        } else {
            $Notify->setReturnParameter('return_code', 'FAIL');
            //数据错误
        }
        $returnXml = $Notify->returnXml();
        echo $returnXml;
    }

    /**
     * 获取支付接口实例
     */
    private function _get_payment_api()
    {
        $inc_file = BASE_PATH . DS . 'api' . DS . 'payment' . DS . $this->payment_code . DS . $this->payment_code . '.php';

        if (is_file($inc_file)) {
            require($inc_file);
        }

        $payment_api = new $this->payment_code();

        return $payment_api;
    }

    /**
     * 获取支付接口信息
     */
    private function _get_payment_config()
    {
        $model_mb_payment = Model('mb_payment');

        //读取接口配置信息
        $condition = array();
        $condition['payment_code'] = $this->payment_code;
        $payment_info = $model_mb_payment->getMbPaymentOpenInfo($condition);

        return $payment_info['payment_config'];
    }

    /**
     * 更新订单状态
     */
    private function _update_order($out_trade_no, $trade_no)
    {
        $model_order = Model('wx_order');
        $logic_payment = Logic('payment');

        $tmp = explode('|', $out_trade_no);
        $out_trade_no = $tmp[0];
        if (!empty($tmp[1])) {
            $order_type = $tmp[1];
        } else {
            $order_pay_info = Model('wx_order')->getOrderPayInfo(array('pay_sn' => $out_trade_no));
            if (empty($order_pay_info)) {
                $order_type = 'v';
            } else {
                $order_type = 'r';
            }
        }

        if ($order_type == 'r') {
            $result = $logic_payment->getRealOrderInfo($out_trade_no);
            //file_put_contents('result_u_r.txt',var_export($result,true));
            if (intval($result['data']['api_pay_state'])) {
                return array('state' => true);
            }
            $order_list = $result['data']['order_list'];
            $result = $logic_payment->updateRealOrder($out_trade_no, $this->payment_code, $order_list, $trade_no);

        } elseif ($order_type == 'v') {
            $result = $logic_payment->getVrOrderInfo($out_trade_no);
            //file_put_contents('result_u_v.txt',var_export($result,true));
            if ($result['data']['order_state'] != ORDER_STATE_NEW) {
                return array('state' => true);
            }
            $result = $logic_payment->updateVrOrder($out_trade_no, $this->payment_code, $result['data'], $trade_no);
        }

        return $result;
    }

}
